package com.khiker.linklist;

public class P21_MergeTwoLists {


    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l1 == null) {
            return l2;
        }
        if(l2 == null) {
            return l1;
        }
        ListNode head = l1.val > l2.val ? l2 : l1;
        ListNode cur = head;
        if (head == l2) {
            l2 = l2.next;
        } else {
            l1 = l1.next;
        }
        while (l1 != null && l2 != null) {
            if (l1.val >= l2.val) {
                cur.next = l2;
                cur = l2;
                l2 = l2.next;
            } else {
                cur.next = l1;
                cur = l1;
                l1 = l1.next;
            }
        }
        cur.next = l2 == null ? l1 : l2;
        return head;
    }

//    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//        if (l1 == null) {
//            return l2;
//        }
//        if (l2 == null) {
//            return l1;
//        }
//        ListNode head = l1.val > l2.val ? l2 : l1;
//        head.next = mergeTwoLists(head.next, head == l1 ? l2 : l1);
//        return head;
//    }
}
